#include "../Base/stdafx.h"
#include "../Base/GameEngine.h"
#include "../Base/DxDevice.h"
#include "../Sprites/Sprite.h"
#include "../Sprites/SpriteRender.h"
#include "Button.h"
#include "../Base/DirectInput.h"

Button::Button(const tstring& text, const D3DXVECTOR3& pos, int width, int height, const tstring& name, bool image): m_SpriteRender(0)
{
	m_Text = text;
	m_Name = name;
	m_Enabled = true;
	m_Armed = false;
	m_Image = image;

	SetBounds((int)pos.x, (int)pos.y, width, height);

	if(m_Image)
	{
		m_Sprite = new Sprite(_T("./Textures/button.bmp"), pos, 3);
		m_SpriteRender = new SpriteRender();
		m_SpriteRender->AddSprite(m_Sprite);
	}
}

Button::~Button()
{
	delete m_SpriteRender;
}

void Button::SetBounds(int x, int y, int width, int height)
{
	m_Pos = D3DXVECTOR3((float)x, (float)y, m_Pos.z);

	m_Width = width;
	m_Height = height;

	if(m_Image)
	{
		float sX = m_Width / m_Sprite->GetWidth();
		float sY = m_Height / m_Sprite->GetHeight();

		m_Sprite->SetPosition(D3DXVECTOR3(m_Pos.x, m_Pos.y, m_Pos.z));
		m_Sprite->SetScale(D3DXVECTOR3(sX, sY, 1));
	}
}

RECT Button::GetRect() const
{
	RECT rc;
	
	rc.left = (int)m_Pos.x;
	rc.right = (int)(rc.left + m_Width);
	rc.top = (int)m_Pos.y; 
	rc.bottom = (int)(rc.top + m_Height);

	return rc;
}

void Button::SetEnabled(bool bEnable)
{
	m_Enabled = bEnable;
}

const tstring& Button::GetText() const
{
	return m_Text;
}

void Button::SetText(const tstring& textRef)
{
	m_Text = textRef;
}

void Button::Paint() const
{

	if(m_Image)	m_SpriteRender->Draw();

	D3DXCOLOR oldKleur;

	if(m_Hover)
	{
		oldKleur = DXDevice::GetSingleton()->GetColor();
		DXDEVICE->SetColor(D3DXCOLOR(0,1,0,1));
	}

	DXDEVICE->DrawText(m_Text, (int)m_Pos.x, (int)m_Pos.y, m_Width, m_Height, DT_CENTER | DT_VCENTER);
	
	if(m_Hover)
		DXDEVICE->SetColor(oldKleur);
}

void Button::Tick(float dTime)
{
	if(m_Enabled)
	{
		POINT pos;
		GetCursorPos(&pos);
		ScreenToClient(GAME_ENGINE->GetWindow(), &pos);

		if(PtInRect(&GetRect(), pos))
		{
			if(DirectInput::GetSingleton()->MouseButtonDown(0))
			{
				m_Armed = true;
				if(m_Image)
					m_Sprite->SetStep(2);
			}else{
				m_Hover = true;
				if(m_Armed)
					CallListeners();
				m_Armed = false;
				if(m_Image)
					m_Sprite->SetStep(1);
			}
		}else{
			m_Hover = false;
			m_Armed = false;
			if(m_Image)
				m_Sprite->SetStep(0);
		}
	}
}